import MyTable from "@/component/common/myTable";
import TableSelects from "@/component/common/tableSelects/tableSelects";
import { useMessageApi } from "@/component/context/messageContext/message";
import { Button, ColorPicker, Flex, Form, Input, Popconfirm, Tag } from "antd";
import { useEffect, useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import tagApi from "./api";
import { MyForm, MyFormProps } from "@/component/common/myForm";
import { MyDrawer } from "@/component/common/myDrawer";

const columns: any = [
  {
    title: "预览",
    dataIndex: "name",
    key: "name",
    align: "center",
    render: (_: any, row: any) => <Tag color={row.color}>{row.name}</Tag>,
  },
];
export interface MyTag {
  id?: string;
  name: string;
  color: string;
}

export default function Tags() {
  const navigate = useNavigate();
  const messageApi = useMessageApi();
  const location = useLocation();
  const [currentTag, setCurrentTag] = useState<MyTag>({} as MyTag);
  const [tagData, setTagData] = useState({
    tags: [],
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: "",
  });
  const [state, setState] = useState<any>({
    loading: false,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [switchState, setSwitchState] = useState({
    isShowAdd: false,
    isShowEdit: false,
  });

  // 获取标签api
  const getTags = (params: any) => {
    setState((oldV: any) => {
      return { ...oldV, loading: true };
    });
    tagApi.getTags(params).then((res: any) => {
      setTagData(res);
      setTimeout(() => {
        setState((oldV: any) => {
          return { ...oldV, loading: false };
        });
      }, 300);
    });
  };
  // 删除标签api
  const delTags = (ids: number[]) => {
    tagApi.delTags(ids).then(() => {
      messageApi.success("删除成功");
      setSelectedRowKeys([]);
      getTags(searchParams);
    });
  };

  // 添加标签弹窗组件
  const [addForm] = Form.useForm();
  const AddTagDrawer = () => {
    const addTagFormConf: MyFormProps = {
      name: "addTagForm",
      form: addForm,
      conf: [
        {
          name: "name",
          label: "名称",
          content: <Input placeholder="请输入标签名" />,
          rules: [{ required: true }],
        },
        {
          name: "color",
          label: "颜色",
          content: <ColorPicker showText />,
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurrentTag({
          ...allValues,
          color: allValues.color?.toHexString() || "",
        });
      },
    };
    const addTag = () => {
      setState((oldV: any) => {
        return { ...oldV, loading: true };
      });
      tagApi
        .addTag(currentTag)
        .then((data) => {
          messageApi.success(data);
          getTags(searchParams);
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false };
          });
        })
        .finally(() => {
          setTimeout(() => {
            setState((oldV: any) => {
              return { ...oldV, loading: false };
            });
          }, 300);
        });
    };
    return (
      <MyDrawer
        open={switchState.isShowAdd}
        footer={
          <Flex gap={"1rem"} justify="right">
            <Button
              onClick={() =>
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: false };
                })
              }
            >
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                addForm
                  .validateFields()
                  .then(() => {
                    addTag();
                  })
                  .catch((err) => {
                    messageApi.error(err.errorFields[0].errors[0]);
                  });
              }}
            >
              确定
            </Button>
          </Flex>
        }
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false };
          })
        }
      >
        <MyForm {...addTagFormConf}></MyForm>
      </MyDrawer>
    );
  };

  // 编辑标签弹窗组件
  const [editForm] = Form.useForm();
  const EditUserDrawer = () => {
    const updateTag = () => {
      setState((oldV: any) => {
        return { ...oldV, loading: true };
      });
      tagApi
        .updateTag(currentTag)
        .then((data) => {
          messageApi.success(data);
          getTags(searchParams);
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false };
          });
        })
        .finally(() => {
          setTimeout(() => {
            setState((oldV: any) => {
              return { ...oldV, loading: false };
            });
          }, 300);
        });
    };
    const editTagFormConf: MyFormProps = {
      name: "editTagForm",
      form: editForm,
      conf: [
        {
          name: "name",
          label: "名称",
          content: <Input placeholder="请输入标签名" />,
          rules: [{ required: true }],
        },
        {
          name: "color",
          label: "颜色",
          content: <ColorPicker showText />,
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurrentTag((oldV) => {
          return {
            ...oldV,
            ...changedValues,
            color: allValues.color?.toHexString() || "",
          };
        });
      },
    };
    return (
      <MyDrawer
        footer={
          <Flex gap={"1rem"} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowEdit: false };
                });
              }}
            >
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                editForm.validateFields().then(() => {
                  updateTag();
                });
              }}
            >
              确定
            </Button>
          </Flex>
        }
        open={switchState.isShowEdit}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false };
          })
        }
      >
        <MyForm {...editTagFormConf}></MyForm>
      </MyDrawer>
    );
  };

  // 过滤器组件
  const Filter = () => {
    const tableOptions = [
      {
        render: (
          <Input
            key="name"
            placeholder="请输入标签名"
            value={searchParams.name}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, name: e.target.value };
              });
            }}
          />
        ),
      },
    ];
    return (
      <TableSelects
        loading={state.loading}
        options={tableOptions}
        source={searchParams}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&name=${searchParams.name}`,
          });
        }}
        buttonChildren={
          <Flex gap={"10px"}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 个标签吗？`}
                onConfirm={() => {
                  delTags(selectedRowKeys);
                }}
              >
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: true };
                });
              }}
            >
              添加
            </Button>
          </Flex>
        }
      ></TableSelects>
    );
  };

  // 表格组件
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const params = {
      pageNum: searchParams.get("pageNum")
        ? Number(searchParams.get("pageNum"))
        : 1,
      pageSize: searchParams.get("pageSize")
        ? Number(searchParams.get("pageSize"))
        : 20,
      name: searchParams.get("name") ? String(searchParams.get("name")) : "",
    };
    setSearchParams(params);
    getTags(params);
  }, [location.search]);
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys);
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    };
    return (
      <MyTable
        loading={state.loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={tagData?.tags}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={tagData.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}&name=${searchParams.name}`,
          });
        }}
        onRow={(record) => ({
          onClick: () => {
            editForm.setFieldsValue({ ...record });
            setCurrentTag(record as MyTag);
            setSwitchState((oldV) => {
              return { ...oldV, isShowEdit: true };
            });
          },
        })}
      ></MyTable>
    );
  }, [
    editForm,
    navigate,
    searchParams.name,
    searchParams.pageSize,
    state.loading,
    tagData?.tags,
    tagData.total,
  ]);

  return (
    <>
      {AddTagDrawer()}
      {EditUserDrawer()}
      {Filter()}
      {Table}
    </>
  );
}
